import { useState, useEffect, MutableRefObject } from "react";
import type { PaginationProps } from 'antd';
import { FetchListParams } from "./typing";

export const useFetchList = (
  fetchList: (params: FetchListParams) => Promise<any>,
  // rowKey: string | number,
  _: string | number,
  allFilter: { filter: any, pagination: PaginationProps },
  onError: (errorMsg: string) => void,
  headerRef: MutableRefObject<{ getHeaderData: () => Promise<{ filter: any }> }>,
  isShowFooter: boolean,
  fetchListDeps: any[],
) => {

  const [fetching, setFetching] = useState(true);
  const [data, setData] = useState<{ total: number, list: any[] } | any[]>(isShowFooter ? { total: 0, list: [], } : []);

  const doFetchList = (current = allFilter.pagination.current) => {
    const { pageSize } = allFilter.pagination;
    const params: any = { page: current, pageSize }
    if (allFilter.filter) params.filter = allFilter.filter;

    const setListData = (realParams: any) => {
      setFetching(true);

      // 非分页的处理方式
      if (!isShowFooter) {
        delete realParams.page;
        delete realParams.pageSize;
        fetchList(realParams).then((data) => {
          if (data) {
            setData(data);
          }
          setFetching(false);
        }).catch((e) => {
          onError(e.msg || e.message)
          setFetching(false);
        });
      } else { // 分页的处理方式
        fetchList(realParams).then((data) => {
          if (data) {
            setData({
              ...data,
              // list: (data.list || []).map((item: any, index: number) => {
              //     item.key = item[rowKey] || index;
              //     return item;
              // })
              list: data.list || [],
            });
          }
          setFetching(false);
        }).catch((e) => {
          onError(e.msg || e.message)
          setFetching(false);
        });
      }

    }

    if (headerRef.current) {
      headerRef.current.getHeaderData().then((resp) => {
        params.filter = resp.filter;
        setListData(params)
      })
    } else {
      setListData(params)
    }
  }

  useEffect(doFetchList, [allFilter, ...fetchListDeps]);

  return { fetching, data, doFetchList }
}
